package com.davy.gridpoint.view;

import android.graphics.Rect;
import android.util.SparseArray;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

import java.util.Arrays;

public class StaggeredGridLayoutManager extends RecyclerView.LayoutManager {

    // 保存每一列的高度
    private int[] mColumnHeights;

    // 保存每个Item的位置信息
    private SparseArray<Rect> mItemRects;

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(
                RecyclerView.LayoutParams.WRAP_CONTENT,
                RecyclerView.LayoutParams.WRAP_CONTENT);
    }

    @Override
    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        super.onLayoutChildren(recycler, state);

        // 初始化每一列的高度
        mColumnHeights = new int[getColumnCount()];
        Arrays.fill(mColumnHeights, 0);

        // 初始化Item的位置信息
        mItemRects = new SparseArray<>();

        int itemCount = getItemCount();
        int itemWidth = getItemWidth();

        for (int i = 0; i < itemCount; i++) {
            View itemView = recycler.getViewForPosition(i);
            addView(itemView);

            // 测量ItemView的宽高
            measureChildWithMargins(itemView, 0, 0);
            int itemHeight = getDecoratedMeasuredHeight(itemView);

            // 找到高度最小的列
            int minColumn = getMinColumn();

            // 计算ItemView的左上右下的坐标
            int left = minColumn * itemWidth;
            int top = mColumnHeights[minColumn];
            int right = left + itemWidth;
            int bottom = top + itemHeight;

            // 保存Item的位置信息
            Rect rect = new Rect(left, top, right, bottom);
            mItemRects.put(i, rect);

            // 更新列的高度
            mColumnHeights[minColumn] = bottom;

            // 布局ItemView
            layoutDecorated(itemView, left, top, right, bottom);
        }
    }

    private int getColumnCount() {
        // 根据实际需求返回列数
        return 3;
    }

    private int getItemWidth() {
        // 根据实际需求返回ItemView的宽度
        return getWidth() / getColumnCount();
    }

    private int getMinColumn() {
        int minColumn = 0;
        int minHeight = mColumnHeights[0];

        for (int i = 1; i < mColumnHeights.length; i++) {
            if (mColumnHeights[i] < minHeight) {
                minColumn = i;
                minHeight = mColumnHeights[i];
            }
        }

        return minColumn;
    }
}
